package com.demo.modules.comm.controller;

import com.demo.common.base.R;
import com.demo.common.utils.EnumUtils;
import com.demo.config.cache.ObjectCacheConfig;
import com.demo.modules.comm.service.MonitorService;
import com.demo.modules.sys.entity.SysConfigEntity;
import com.demo.modules.sys.entity.SysDictEntity;
import com.demo.modules.sys.entity.SysDictValEntity;
import com.demo.modules.sys.entity.SysOrgEntity;
import com.demo.modules.sys.service.SysConfigService;
import com.demo.modules.sys.service.SysDictService;
import com.demo.modules.sys.service.SysDictValService;
import com.demo.modules.sys.service.SysOrgService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 公共API
 */
@RestController
@RequestMapping("/comm")
@AllArgsConstructor
public class CommonController {

    private SysConfigService sysConfigService;
    private SysOrgService orgService;
    private SysDictService sysDictService;
    private SysDictValService sysDictValService;
    private ObjectCacheConfig cacheConfig;
    //系统-服务监控管理
    private MonitorService serverService;

    /**
     * 查询服务监控
     */
    @GetMapping("/monitor/query")
    public R query() {
        return R.ok(serverService.getServers());
    }

    @GetMapping("/enums/")
    public R getEnums() {
        Map<String, Object> enumOptions = EnumUtils.enumsToOptions();
        return R.ok(enumOptions);
    }

    /**
     * 获取系统参数，此参数在参数管理节点配置
     */
    @GetMapping("/config/list")
    public R<List<SysConfigEntity>> getConfigList() {
        List<SysConfigEntity> list = sysConfigService.list();

        return R.ok(list);
    }

    /**
     * 组织机构档案（全部）
     */
    @GetMapping("/org/all")
    public R<List<SysOrgEntity>> orgAll() {
        List<SysOrgEntity> list = orgService.listAll();

        return R.ok(list);
    }

    /**
     * 数据字典档案（全部）
     */
    @GetMapping("/dict/all")
    public R<List<SysDictEntity>> dictAll() {
        List<SysDictEntity> dictList = sysDictService.listAll();
        List<SysDictValEntity> valList = sysDictValService.listAll();

        dictList.forEach(dict -> {
            List<SysDictValEntity> list = new ArrayList<>();
            valList.forEach(val -> {
                if (dict.getId().equals(val.getDictId())) {
                    list.add(val);
                }
            });
            dict.setValList(list);
        });

        return R.ok(dictList);
    }

    /**
     * 更新后台数据缓存
     */
    @GetMapping("/updateCache")
    public R updateCache() {
        cacheConfig.createCache();
        return R.ok("更新后台数据缓存成功");
    }

}
